import 'dart:convert' show json;
import 'package:flutter/cupertino.dart';
import 'base_chart_formatter.dart';
import 'base_model_asT.dart';
import 'package:ribo_base_core/base_styles/base_chart_style.dart';

class BaseChartFunnelModel {
  /// https://echarts.apache.org/zh/option.html#tooltip.formatter
  BaseChartFormatter tooltipFormatter;

  /// https://echarts.apache.org/zh/option.html#series-pie.label.formatter
  BaseChartFormatter labelFormatter;

  /// 图表样式
  BaseChartStyle style;

  ///排序方式
  String sort;

  /// 图表数据
  List<BaseChartFunnelData> data;

  BaseChartFunnelModel({
    this.tooltipFormatter,
    this.labelFormatter,
    this.style,
    this.sort='descending',
    @required this.data,
  });

  factory BaseChartFunnelModel.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) {
      return null;
    }

    final List<BaseChartFunnelData> data =
        jsonRes['data'] is List ? <BaseChartFunnelData>[] : null;
    if (data != null) {
      for (final dynamic item in jsonRes['data']) {
        if (item != null) {
          data.add(
              BaseChartFunnelData.fromJson(asT<Map<String, dynamic>>(item)));
        }
      }
    }
    return BaseChartFunnelModel(
      tooltipFormatter: asT<BaseChartFormatter>(jsonRes['tooltipFormatter']),
      labelFormatter: asT<BaseChartFormatter>(jsonRes['labelFormatter']),
      style: asT<BaseChartStyle>(jsonRes['style']),
      sort: asT<String>(jsonRes['sort']),
      data: data,
    );
  }

  Map<String, dynamic> toJson() => <String, dynamic>{
        'tooltipFormatter': tooltipFormatter,
        'labelFormatter': labelFormatter,
        'style': style,
        'sort': sort,
        'data': data,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}


class BaseChartFunnelData {
  BaseChartFunnelData({String name, this.value, this.itemStyle})
      : this.name = name.substring(name.lastIndexOf('-')+1); //只显示最后的日期

  factory BaseChartFunnelData.fromJson(Map<String, dynamic> jsonRes) =>
      jsonRes == null
          ? null
          : BaseChartFunnelData(
              name: asT<String>(jsonRes['name']),
              value: asT<double>(jsonRes['value']),
              itemStyle:
                  asT<BaseChartFunnelDataItemStyle>(jsonRes['itemStyle']),
            );

  /// 数据名称
  String name;

  /// 数据值
  double value;

  BaseChartFunnelDataItemStyle itemStyle;

  Map<String, dynamic> toJson() =>
      <String, dynamic>{'name': name, 'value': value, 'itemStyle': itemStyle};

  @override
  String toString() {
    return json.encode(this);
  }
}

class BaseChartFunnelDataItemStyle {
  String color;
  String borderColor;

  Map<String, dynamic> toJson() {
    return {'color': color, 'borderColor': borderColor};
  }

  BaseChartFunnelDataItemStyle({this.color, this.borderColor});
}
